package com.usian.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.search.dto.UserSearchDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.search.feign.BehaviorFeign;
import com.usian.search.service.ApUserSearchService;
import com.usian.search.service.SearchService;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private ApUserSearchService apUserSearchService;

    @Autowired
    private BehaviorFeign behaviorFeign;

    @Override
    public ResponseResult search(UserSearchDto dto) {

        List<Map> list = new ArrayList<>();
        try {
            //1.检查参数
            if (dto == null || StringUtils.isBlank(dto.getSearchWords())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }

            //获取用户信息
            ApUser user = AppThreadLocalUtils.getUser();
            if (user == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            }

            //获取行为实体
            ApBehaviorEntry apBehaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
            if (apBehaviorEntry == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            apUserSearchService.insert(apBehaviorEntry.getId(),dto.getSearchWords());


            SearchRequest appInfoArticle = new SearchRequest("app_info_article");

            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();//用于组合条件

            QueryStringQueryBuilder queryStringQueryBuilder =
                    QueryBuilders.queryStringQuery(dto.getSearchWords()).field("title").field("content").defaultOperator(Operator.OR);

            boolQuery.must(queryStringQueryBuilder);

            //区间查询
            RangeQueryBuilder publishTime = QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime());

            boolQuery.filter(publishTime);

            searchSourceBuilder.query(boolQuery);
            searchSourceBuilder.sort("publishTime", SortOrder.DESC);
            searchSourceBuilder.from(dto.getPageNum());
            searchSourceBuilder.size(dto.getPageSize());

            appInfoArticle.source(searchSourceBuilder);

            SearchResponse search = restHighLevelClient.search(appInfoArticle, RequestOptions.DEFAULT);
            SearchHit[] searchHits = search.getHits().getHits();
            for (SearchHit searchHit : searchHits) {
                String sourceAsString = searchHit.getSourceAsString();
                Map map = JSON.parseObject(sourceAsString, Map.class);
                list.add(map);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return ResponseResult.okResult(list);
    }
}
